<?php
/**
 * Created by PhpStorm.
 * User: coolinmind
 * Date: 01/03/2019
 * Time: 16:50
 */

namespace App\Services\UCenter\UCenter;


use App\Models\Cargo\WayBill;
use App\Models\Comment\CommentContents;
use App\Models\Comment\Comments;
use App\Services\Setting\SettingIndex;
use DB;

class CommentLogic
{
    /**
     * 发表评论
     * @param $data
     * @return array
     */
    public function addComment($data)
    {
        //判断是否已经发表评论
        $checkRes = Comments::where(['from_user_id' => $data['user_id'], 'waybill_id' => $data['waybill_id']])->first();
        if($checkRes)
            return auto_failure(null, '您已经评论过该运单');

        $preData = [
            'from_user_id' => $data['user_id'],
            'waybill_id' => $data['waybill_id'],
            'created_at' => date('Y-m-d H:i:s', NOW),
            'updated_at' => date('Y-m-d H:i:s', NOW),
        ];
        $waybillMod = WayBill::where(['id' => $data['waybill_id']])->first();

        //判断发表评价者是货主还是车主
        if (in_array(163, explode(',', $data['role_ids']))) {
            $preData['to_user_id'] = $waybillMod->driver_id;
            $waybillMod->is_owner_comment = 1;
            if ($waybillMod->is_driver_comment == 1) {
                $waybillMod->status = 4;
            }
        }else{
            $preData['to_user_id'] = $waybillMod->owner_id;
            $waybillMod->is_driver_comment = 1;
            if ($waybillMod->is_owner_comment == 1) {
                $waybillMod->status = 4;
            }
        }

        $content = explode(',', $data['content']);

        //开启事务
        DB::beginTransaction();
        try {
            $r = Comments::insertGetId($preData);

            foreach ($content as $v) {
                $conData = [
                    'to_user_id' => $preData['to_user_id'],
                    'comment_id' => $r,
                    'content' => $v,
                    'created_at' => date('Y-m-d H:i:s', NOW),
                    'updated_at' => date('Y-m-d H:i:s', NOW),
                ];

                $res = CommentContents::insert($conData);
                if(!$res){
                    DB::rollBack();
                    return auto_failure($res, '发表评论失败');
                }
            }
            $waybillMod->save(); // 双方互评后，更新运单状态
            DB::commit();
            return auto_success($r, '发表评论成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return auto_failure('数据库异常', '发表评论失败');
        }
    }

    /**
     * 获取用户评价标签统计数据
     * @param $data
     */
    public function getCommentStatistics($data)
    {
        $res = CommentContents::where(['to_user_id' => $data['user_id']])
            ->select(DB::raw('content tag, count(*) number'))
            ->groupBy('content')
            ->get()
            ->toArray();
        return auto_return($res);
    }
}
